package com.codeshellme.bookmanager.service.impl;

import com.codeshellme.bookmanager.dao.BookBorrowDao;
import com.codeshellme.bookmanager.dao.BookStockDao;
import com.codeshellme.bookmanager.dto.BookBorrow;
import com.codeshellme.bookmanager.service.BookBorrowService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class BookBorrowServiceImpl implements BookBorrowService {

    @Autowired
    private BookBorrowDao bookBorrowDao;

    @Autowired
    private BookStockDao bookStockDao;

    @Override
    public PageInfo<Map<String, Object>> queryAllBookBorrows(
            String book_name, Integer type_id, Integer author_id, String status,
            Integer student_id, String student_name,
            String bdate_start, String bdate_end,
            String rdate_start, String rdate_end,
            Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> books = bookBorrowDao.queryAllBookBorrows(
                book_name, type_id, author_id, status,
                student_id, student_name,
                bdate_start, bdate_end,
                rdate_start, rdate_end);
        return new PageInfo<>(books);
    }

    @Override
    @Transactional
    public int bookReturn(Integer borrowId, Integer stockId) {
        // 修改 book_borrow 状态
        bookBorrowDao.bookReturn(borrowId);

        // 增加库存
        bookStockDao.updateBookStockNum(stockId, 1);

        return 0;
    }

    @Override
    @Transactional
    public int bookBorrowSave(List<BookBorrow> borrows) {
        // 第一步 插入 book_borrow 表
        bookBorrowDao.insertBorrows(borrows);

        // 第二步 扣库存
        for (BookBorrow borrow: borrows) {
            bookStockDao.updateBookStockNum(borrow.getStock_id(), -1);
        }

        return 0;
    }
}
